<template>
  <div class="diagnosis-container">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>智能眼底分析</h3>
          <el-button
            type="primary"
            size="small"
            @click="patients.push(initPatient())"
            >添加患者</el-button
          >
        </div>
      </template>
      <div
        v-for="(patient, index) in patients"
        :key="index"
        class="patient-card"
      >
        <div class="patient-info">
          <el-input v-model="patient.name" placeholder="姓名"></el-input>
          <el-input v-model="patient.idCard" placeholder="身份证号"></el-input>
          <el-input-number
            v-model="patient.age"
            :min="0"
            :max="120"
          ></el-input-number>
          <el-select v-model="patient.sex">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
          <el-button
            v-if="patients.length > 1"
            type="danger"
            @click="patients.splice(index, 1)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
        <div class="eye-upload">
          <div class="upload-item">
            <el-upload
              :auto-upload="false"
              :show-file-list="false"
              :on-change="(file:any) => handleEyeImage(index, 'left', file.raw)"
            >
              <template #trigger>
                <el-button type="primary">上传左眼图像</el-button>
              </template>
            </el-upload>
            <img
              v-if="patient.leftEye"
              :src="previewImage(patient.leftEye)"
              class="eye-preview"
            />
          </div>

          <div class="upload-item">
            <el-upload
              :auto-upload="false"
              :show-file-list="false"
              :on-change="(file:any) => handleEyeImage(index, 'right', file.raw)"
            >
              <template #trigger>
                <el-button type="primary">上传右眼图像</el-button>
              </template>
            </el-upload>
            <img
              v-if="patient.rightEye"
              :src="previewImage(patient.rightEye)"
              class="eye-preview"
            />
          </div>
        </div>
      </div>
      <el-button
        type="success"
        size="large"
        class="submit-btn"
        @click="handleUpload"
        >开始智能分析</el-button
      >
    </el-card>
    <CaseChart v-if="chartData.length" :data="chartData"></CaseChart>
    <ImageList v-if="imageData.length" :images="imageData"></ImageList>
  </div>
</template>

<script setup lang="ts">
import { Delete } from "@element-plus/icons-vue";
import CaseChart from "@/components/CaseChart.vue";
import ImageList from "@/components/ImageList.vue";
import { ref, getCurrentInstance } from "vue";
const instance = getCurrentInstance();
const proxy = instance?.proxy as any;
import { useUserStore } from "@/stores/userStore";
const userStore = useUserStore();
import { useImageStore } from "@/stores/imageStore";
const imageStore = useImageStore();
import { usePatientStore } from "@/stores/patientStore";
const patientStore = usePatientStore();

import { PatientDiagInfo } from "@/types/patient";
import { DiseaseCase } from "@/types/imageAndFile";
import verify from "@/utils/verify";

const initPatient = () => {
  const patient: PatientDiagInfo = {
    name: "",
    sex: "男",
    idCard: "",
    age: 0,
    leftEye: null,
    rightEye: null,
  };
  return patient;
};
const patients = ref<PatientDiagInfo[]>([
  {
    name: "",
    idCard: "",
    age: 0,
    sex: "男",
    leftEye: null,
    rightEye: null,
  },
]);

//渲染
const chartData = ref<DiseaseCase[]>([]);
const imageData = ref<any>([]);

const previewImage = (file: File) => {
  return URL.createObjectURL(file);
};

const handleEyeImage = (index: number, side: "left" | "right", file: File) => {
  if (index < 0 || index >= patients.value.length) return;
  (patients.value[index] as PatientDiagInfo)[`${side}Eye`] = file;
};

//验证
const validateSubmission = () => {
  return patients.value.every((patient: PatientDiagInfo, index: number) => {
    const valid: any = Object.values(patient).every((v) => {
      if (v === null) return false;
      return typeof v === "object" ? !!v.name : !!v;
    });

    if (!valid) {
      proxy.message.warning(`第${index + 1}位患者信息不完整`);
      return false;
    }
    if (!verify.regs.idCard.test(patient.idCard)) {
      proxy.message.warning(`第${index + 1}位患者身份证号无效`);
      return false;
    }
    return true;
  });
};

//提交数据
const handleUpload = async () => {
  if (!validateSubmission()) return;
  const formData = new FormData();
  const patientData = patients.value.map((p) => ({
    name: p.name,
    idCard: p.idCard,
    age: p.age,
    sex: p.sex,
  }));
  formData.append(
    "patients",
    new Blob([JSON.stringify(patientData)], {
      type: "application/json",
    }),
    "patients.json"
  );

  patients.value.forEach((patient) => {
    if (patient.leftEye) formData.append(`leftImage`, patient.leftEye);
    if (patient.rightEye) formData.append(`rightImage`, patient.rightEye);
  });

  try {
    let result: any = await proxy.request({
      method: "post",
      url: proxy.api.diagnosisAnalyze,
      data: formData as FormData,
      headers: {
        authentication: userStore.getUserData().token,
        "Content-Type": "multipart/form-data",
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      proxy.message.success("分析请求已提交");
      const recordIds: number[] = result.data.map((item: any) => item.recordId);
      const patientIds: number[] = result.data.map(
        (item: any) => item.patientId
      );
      //存储到patientStore
      patients.value.forEach((patient: PatientDiagInfo, index: number) => {
        const existingPatient = patientStore.findPatientByIdCard(
          patient.idCard
        );
        if (existingPatient) {
          //refresh
          patientStore.updatePatient(
            existingPatient.patientId as number,
            recordIds[index] as number
          );
        } else {
          patientStore.addPatient({
            ...patient,
            recordId: recordIds[index],
            patientId: patientIds[index],
            reportId: null,
            reportGenerated: false,
          });
        }
      });
      //获取左右图片
      const leftImages: File[] = patients.value.map(
        (patient: PatientDiagInfo) => {
          return patient.leftEye as File;
        }
      );
      const rightImages: File[] = patients.value.map(
        (patient: PatientDiagInfo) => {
          return patient.rightEye as File;
        }
      );
      //使用游客接口获取图片渲染
      let analyzeResult: any = await imageStore.guestAnalyze(
        leftImages,
        rightImages
      );
      if (!analyzeResult) return;
      if (analyzeResult.code === 1) {
        chartData.value = imageStore.cases;
        imageData.value = imageStore.processedImages.map((c) => ({
          leftImage: c.leftImage,
          rightImages: c.rightImage,
          diseaseResult: {
            leftD: c.leftDiseaseResult,
            rightD: c.rightDiseaseResult,
          },
          confidence: { leftC: c.leftConfidence, rightC: c.rightConfidence },
        }));
      } else {
        proxy.message.warning("图片获取分析数据失败，请检查网络连接");
      }
      patients.value = [initPatient()];
    } else {
      proxy.message.warning("提交失败，请检查网络连接1");
    }
  } catch (error) {
    proxy.message.error("提交失败，请检查网络连接");
  }
};
</script>

<style scoped>
.diagnosis-container {
  background: #f0f2f5;
  margin-top: 20px;
}

.upload-card {
  width: 100%;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
}

.patient-card {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.patient-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.eye-upload {
  display: flex;
  gap: 24px;
  margin-top: 12px;
}

.upload-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.eye-preview {
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  display: block;
}

.eye-preview:hover {
  transform: scale(1.05);
  cursor: pointer;
}

.upload-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.eye-upload {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

@media (max-width: 768px) {
  .eye-preview {
    width: 60px;
    height: 60px;
  }
}

.el-icon {
  margin-right: 5px;
}

.el-button--danger {
  padding: 8px 12px;
}
</style>
